<template>
    <el-dialog v-model="createFolderVisible" class="custom-dialog" width="544px" :show-close='false'
        :close-on-click-modal="false" modal-class="dialog-center" :before-close="handleClose">
        <div class="custom-dialog-header">
            <div class="title-box">
                <div class="title">
                    {{ createType == 'add' ? $t('message.text.createNewFolder') : $t('message.text.editNewFolder') }}
                </div>
            </div>
            <svg class="close-icon" @click="handleClose">
                <use xlink:href="#keowledge-danchuangguanbi1"></use>
            </svg>
        </div>
        <div class="custom-dialog-body">
            <el-form :model="folderForm" :rules="folderRules" size="large" ref="folderFormRef">
                <el-form-item prop="name">
                    <div class="custom-form-title"><span class="require">*</span>{{ fileType == 'add_directory' ?
                        $t('message.form.folderName') : $t('message.form.fileName') }}
                    </div>
                    <el-input v-model="folderForm.name"
                        :placeholder="`${$t('message.placeholder.pleaseInput')}${fileType == 'add_directory' ? $t('message.form.folderName') : $t('message.form.fileName')}`" />
                    <!-- <div class="custom-form-tips">请不要输入 /、#，否则分享该文档将失效</div> -->
                </el-form-item>
                <el-form-item prop="urlAddress" v-if="fileType == 'url_address'">
                    <div class="custom-form-title"><span class="require">*</span>{{ $t('message.form.fileLinkAddress')
                        }}
                    </div>
                    <el-input v-model="folderForm.urlAddress"
                        :placeholder="$t('message.placeholder.pleaseFileLinkAdd')" />
                    <!-- <div class="custom-form-tips">请不要输入 /、#，否则分享该文档将失效</div> -->
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <div class="custom-dialog-footer">
                <el-button @click="handleClose">{{ $t('message.buttons.cancal') }}</el-button>
                <el-button type="primary" @click="handleSave">{{ $t('message.buttons.submit') }}</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import {
    ref,
    reactive,
    toRefs,
    watch,
    onMounted,
    getCurrentInstance
} from 'vue'
import type { ComponentInternalInstance } from 'vue'
import { useRouter } from "vue-router"
import type { FormRules } from 'element-plus'
import { addLibrary } from '@/api/knowledge'
import { setLibrary } from '@/api/common'
import { useHookI18n } from '@/hooks/i18n'

const { locale, $t } = useHookI18n()
const router = useRouter();
const instance: any = getCurrentInstance() as ComponentInternalInstance;
const proxy: any = instance.proxy as any; // 访问 proxy 属性
const emit = defineEmits(["createSuccess"])
const props = defineProps({
    saveObj: {
        type: Object,
        default() {
            return {}
        }
    }
})
const createType = ref('')
const fileType = ref('')
const createFolderVisible = ref(false)
const folderFormRef = ref()
const folderForm = ref({
    name: '',
    urlAddress: ''
})
const saveObj = ref({
    knowledgeId: '',
    id: '',
    type: "",
    parentId: ''
})
const folderRules = ref<FormRules>({
    name: [{
        validator: (rule: any, value: any, callback: any) => {
            if (!value) {
                let str = $t('message.placeholder.pleaseInput')
                str += fileType.value == 'add_directory' ? $t('message.form.folderName') : $t('message.form.fileName')
                callback(new Error(str))
            } else {
                let reg = /([:/?\*<>\&|\{}\!:\'$%\^])/g
                if (reg.test(value)) {
                    callback(new Error($t('message.placeholder.noInputCharacters')))
                } else {
                    callback()
                }
            }
        }
    }],
    urlAddress: [{
        validator: (rule: any, value: any, callback: any) => {
            if (!value) {
                callback(new Error($t('message.placeholder.pleaseFileLink')))
            } else {
                let reg = /(http|https):\/\/([\w.]+\/?)\S*/
                if (!reg.test(value)) {
                    callback(new Error($t('message.placeholder.pleaseLinkStart')));
                }
                callback()
            }
        }
    }]
})

function init(type, data, fType) {
    saveObj.value = data
    createType.value = type
    fileType.value = fType
    if (type == 'edit') {
        folderForm.value = JSON.parse(JSON.stringify(data))
    }
    createFolderVisible.value = true
}

function handleClose() {
    folderForm.value = {
        name: '',
        urlAddress: ''
    }
    folderFormRef.value.resetFields()
    createFolderVisible.value = false
}

function handleSave() {
    folderFormRef.value.validate(valid => {
        if (valid) {
            if (createType.value == 'add') {
                addLibrary({
                    fileType: fileType.value == 'add_directory' ? 'directory' : fileType.value,
                    urlAddress: fileType.value == 'add_directory' ? null : folderForm.value.urlAddress,
                    id: saveObj.value.knowledgeId || saveObj.value.id,
                    name: folderForm.value.name,
                    parentId: ['directory', 'knowledge'].indexOf(saveObj.value.type) != -1 ? saveObj.value.id : saveObj.value.parentId,
                    knowledgeId: saveObj.value.knowledgeId || saveObj.value.id
                }).then(res => {
                    if (res.data.code == 0) {
                        proxy.$onePrompt.$oneNotify({
                            message: fileType.value == 'add_directory' ? $t('message.message.createFolderSuccess') : $t('message.message.createUrlSuccess'),
                            type: 'success',
                            position: 'bottom-right',
                            title: $t('message.prompt')
                        })
                        emit('createSuccess', res.data.data)
                        handleClose()
                    }
                })
            } else {
                if (folderForm.value.children) delete folderForm.value.children
                if (folderForm.value.label) delete folderForm.value.label
                if (folderForm.value.level) delete folderForm.value.level

                setLibrary({
                    ...folderForm.value,
                    filePath: null,
                    bucketName: null,
                    transfer: null
                }).then(res => {
                    if (res.data.code == 0) {
                        proxy.$onePrompt.$oneNotify({
                            message: fileType.value == 'add_directory' ? $t('message.message.editFolderSuccess') : $t('message.message.editUrlSuccess'),
                            type: 'success',
                            position: 'bottom-right',
                            title: $t('message.prompt')
                        })
                        emit('createSuccess', res.data.data)
                        handleClose()
                    }
                })
            }
        }
    })
}

defineExpose({
    init
})
</script>
<style lang="scss" scoped>
.custom-dialog-body {
    padding: 24px 32px;

    .custom-form-tips {
        height: 20px;
        line-height: 20px;
        font-size: 12px;
        color: #6F7588;
    }
}
</style>